import axios from "axios";
import React, { useState, useReducer, useContext, useRef, useImperativeHandle } from "react";


const Box = React.forwardRef((props, ref) => {

    const [count, setCount] = useState(100)

    // useImperativeHandle 自定义暴露给父组件 ref 的内容
    useImperativeHandle(ref, () => {
        // return 出去的内容，就是自定义暴露出去的内容
        return {
            msg: '辣条',
            count,
            add() {
                setCount(count + 1)
            }
        }
    })

    return <>
        {/* <h1 ref={ref}>Box - {count}</h1> */}
        <h1>Box - {count}</h1>
    </>
})

function App() {

    // 创建一个 ref
    const boxRef = useRef(null)

    return <div>
        <h1 >App</h1>
        <button onClick={() => {
            console.log(boxRef);

            // 调用子组件的方法
            boxRef.current.add()

        }}>点击获取内容</button>
        <hr />


        {/* 给函数组件设置 ref */}
        <Box ref={boxRef}></Box>



    </div>
}


export default App